package com.tjh.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjh.common.exception.NoStockException;
import com.tjh.common.to.mq.OrderTo;
import com.tjh.common.to.mq.SeckillOrderTo;
import com.tjh.common.utils.PageUtils;
import com.tjh.common.utils.Query;
import com.tjh.common.utils.R;
import com.tjh.common.vo.MemberRespVo;
import com.tjh.gulimall.order.constant.OrderConstant;
import com.tjh.gulimall.order.dao.OrderDao;
import com.tjh.gulimall.order.entity.OrderEntity;
import com.tjh.gulimall.order.entity.OrderItemEntity;
import com.tjh.gulimall.order.entity.PaymentInfoEntity;
import com.tjh.gulimall.order.enume.OrderStatusEnum;
import com.tjh.gulimall.order.feign.CartFeignService;
import com.tjh.gulimall.order.feign.MemberFeignService;
import com.tjh.gulimall.order.feign.ProductFeignService;
import com.tjh.gulimall.order.feign.WmsFeignService;
import com.tjh.gulimall.order.interceptor.LoginUserInterceptor;
import com.tjh.gulimall.order.service.OrderItemService;
import com.tjh.gulimall.order.service.OrderService;
import com.tjh.gulimall.order.service.PaymentInfoService;
import com.tjh.gulimall.order.to.OrderCreateTo;
import com.tjh.gulimall.order.vo.FareVo;
import com.tjh.gulimall.order.vo.MemberAddressVo;
import com.tjh.gulimall.order.vo.OrderConfirmVo;
import com.tjh.gulimall.order.vo.OrderItemVo;
import com.tjh.gulimall.order.vo.OrderSubmitVo;
import com.tjh.gulimall.order.vo.PayAsyncVo;
import com.tjh.gulimall.order.vo.PayVo;
import com.tjh.gulimall.order.vo.SkuStockVo;
import com.tjh.gulimall.order.vo.SpuInfoVo;
import com.tjh.gulimall.order.vo.SubmitOrderResponseVo;
import com.tjh.gulimall.order.vo.WareSkuLockVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Create by koala on 2021-01-24 21:50:38
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    //day117
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        System.out.println("主线程……" + Thread.currentThread().getId());

        /**
         * day118：解决Feign异步调用丢失请求头问题
         */
        //获取之前的请求，传递给异步任务的线程
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //使用异步编排
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            System.out.println("member线程……" + Thread.currentThread().getId());
            //day118：每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1.远程查询所有的收货地址列表
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            System.out.println("cart线程……" + Thread.currentThread().getId());
            //day118：每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2.远程查询购物车所有选中的购物项
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(() -> {

            //day119：查询sku是否有库存
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            //查询是否有库存
            R hasStock = wmsFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {});
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }

        }, executor);


        //3.查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

        //4.其他数据自动计算

        // day121：5.防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        return confirmVo;
    }

    /**
     * day125：本地事务失效问题
     * 同一个对象内事务方法互调默认失效，原因：绕过了代理对象
     * 事务使用代理对象来控制的
     */
    @Transactional(timeout = 30) //a事务的所有设置就传播到了和他公用一个事务的方法
    public void a() {
        //做如下操作，则此时b，c做任何设置都没用。都是和a公用一个事务
        /*this.b(); 没用
        this.c(); 没用*/

        //这边假设调用远程服务，因为不是同一个对象内事务方法互调，无本地事务失效问题
        /*bService.b(); //属于a事务范畴
        cService.c(); //属于新事务范畴(a事务执行出错，c不发生回滚)*/

        //最终解决方案如下：
        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
        orderService.b();
        orderService.c();
        int i = 10 / 0;
    }

    @Transactional(propagation = Propagation.REQUIRED, timeout = 2)
    public void b() {
        //7s
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 20)
    public void c() {

    }

    //day122
    /**
     * day124：本地事务，在分布式系统，只能控制住自己的回滚，控制不了其他服务的回滚
     * 分布式事务：最大原因。网络问题+分布式机器。
     */
    /**
     * @GlobalTransactional--》day126：MySeataConfig开启seata全局事务 ，此接口业务场景为高并发接口不适合使用seata进行分布式事务控制（这边只做演示）
     * 测试：
     *      0、解开注释：
     *          1）@GlobalTransactional//day126
     *          2）int i=10/0;  //模拟让订单回滚，库存不回滚
     *      1、浏览器访问购物车页面（登录状态）：http://cart.gulimall.com/cart.html
     *      2、点击结算按钮去结算
     *      3、进入结算页
     *      4、点击提交订单按钮
     *      5、查看有货状态下
     *          数据库 gulimall_wms下的表wms_ware_sku的锁库状态（相关字段：stock_locked）
     *          数据库 gulimall_oms下的表oms_order和oms_order_item的订单及订单项数据的生成情况（相关字段：order_sn）
     *      6、最终效果应该是表wms_ware_sku、oms_order、oms_order_item未发生任何改动
     */
    //@GlobalTransactional//day126
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        response.setCode(0);
        confirmVoThreadLocal.set(vo);
        //1.验证令牌[令牌的对比和删除必须保证原子性]
        //使用lura脚本 0令牌失败 1删除成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()
        ), orderToken);
        if (result == 0){
            //令牌验证失败
            response.setCode(1);
            return response;
        }else {
            //令牌验证成功
            //下单  去创建订单，验令牌，验价格，锁库存……
            //1.创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            //2.验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比
                //……
                //TODO:3.保存订单
                saveOrder(order);
                //day123：4.库存锁定,只要有异常回滚订单数据
                //订单号、所有订单项（skuId,skuName,num）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                // TODO: 2020/11/16 远程锁库存
                /**
                 * day124：库存成功了，但是网络原因超时了，订单回滚，库存会不回滚
                 * 场景：
                 *      1、远程服务假失败：
                 *              远程服务其实成功了，由于网络故障等没有返回
                 *              导致：订单回滚，库存却扣减
                 *      2、远程服务执行完成，下面的其他方法出现问题、
                 *              导致：已执行的远程请求，肯定不能回滚
                 * 测试：
                 *      0、解开注释：
                 *          1）int i=10/0;  //模拟让订单回滚，库存不回滚
                 *      1、浏览器访问购物车页面（登录状态）：http://cart.gulimall.com/cart.html
                 *      2、点击结算按钮去结算
                 *      3、进入结算页
                 *      4、点击提交订单按钮
                 *      5、查看有货状态下
                 *          数据库 gulimall_wms下的表wms_ware_sku的锁库状态（相关字段：stock_locked）
                 *          数据库 gulimall_oms下的表oms_order和oms_order_item的订单及订单项数据的生成情况（相关字段：order_sn）
                 */
                //为了保证高并发。库存服务自己回滚---->可以发消息给库存服务
                //库存服务本身也可以使用自动解锁模式   消息队列
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //锁成功了
                    response.setOrder(order.getOrder());

                    // day124：本地事务在分布式下的问题演示： TODO: 2020/11/16 假设这边做 远程扣减积分操作
                    //int i= 10/0;  //模拟让订单回滚，库存不回滚

                    //day131：TODO: 2020/11/19 订单创建成功发送消息给mq
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return response;
                }else {
                    //锁定失败
                    String msg = (String)r.get("msg");
                    throw new NoStockException(msg);
                }
            }else {
                //金额对比失败
                response.setCode(2);
                return response;
            }
        }
    }

    //day122：创建订单，订单项等信息
    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();
        //1.生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        //2.获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        //3.验价 计算价格、积分等相关信息
        computePrice(orderEntity,itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    //day122：
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //创建订单号
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        //会员id
        entity.setMemberId(memberRespVo.getId());
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        //获取收货地址信息
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {});
        //设置运费信息
        entity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);//确认收货天数

        return entity;
    }

    /**
     * day122：构建订单项数据
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn){
        //最后确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems!=null &&currentUserCartItems.size()>0){
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }

        return null;
    }

    /**
     * day122：构建某一个订单项
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1.订单信息，订单号
        //2.商品的spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //3.商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPrice(cartItem.getPrice());
        itemEntity.setSkuPic(cartItem.getImage());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4.优惠信息【不做】
        //5.积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6.订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额 总额-各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity()));
        BigDecimal realAmount = orign.subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(realAmount);
        return itemEntity;
    }

    //day122
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额，叠加每个订单项的总额信息
        for(OrderItemEntity entity:itemEntities){
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getIntegrationAmount());
            total = total.add(entity.getRealAmount());
            gift =gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //1.订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);
    }

    /**
     * day122：保存订单数据
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        for (OrderItemEntity entity:orderItems){
            orderItemService.save(entity);
        }
    }

    //day130
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /**
     * day131：订单超时未支付进行关单操作
     * 测试：
     *      0、注释以下内容（com.tjh.gulimall.order.service.impl.OrderServiceImpl）：
     *          1）@GlobalTransactional//day126
     *          2）int i=10/0;  //模拟让订单回滚，库存不回滚
     *      1、浏览器访问购物车页面（登录状态）：http://cart.gulimall.com/cart.html
     *      2、点击结算按钮去结算
     *      3、进入结算页
     *      4、点击提交订单按钮
     *      5、浏览器访问（rabbitMQ服务器）：http://127.0.0.1:15672/#/ Queues--》order.delay.queue、order.release.order.queue，stock.delay.queue、stock.release.stock.queue 观察数据变化
     *      6、查看有货状态下
     *          数据库 gulimall_wms下的表wms_ware_sku的锁库状态（相关字段：stock_locked）
     *          数据库 gulimall_oms下的表oms_order的订单数据的生成情况（相关字段：status）
     *          数据库 gulimall_wms下的表wms_ware_order_task_detail的锁库状态（相关字段：lock_status）
     *      7、最终效果应该是表wms_ware_sku未发生任何改动，表oms_order产生一条已取消状态的订单数据，表wms_ware_order_task_detail产生n条相关库存已解锁数据
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            //发给MQ一个
            try {
                //TODO 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）。
                //TODO 定期扫描数据库将失败的消息再发送一遍；
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                //TODO 将没发送成功的消息进行重试发送。
                //while()
            }
        }
    }

    //day132：支付宝支付
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);

        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);

        payVo.setSubject(entity.getSkuName());
        payVo.setBody(entity.getSkuAttrsVals());

        return payVo;
    }

    /**
     * day133：处理支付宝的支付结果
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(infoEntity);

        //2、修改订单的状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    //day132：分页查询当前登录用户的所有订单
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    //day139：创建秒杀订单
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        //TODO 获取当前SKU的详细信息进行设置  productFeignService.getSpuInfoBySkuId()
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());

        orderItemService.save(orderItemEntity);
    }

}